package com.blog.blog.config;

import com.blog.blog.service.BackupService;
import com.blog.blog.vo.OssFileVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 备份定时任务配置
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "app.backup.enabled", havingValue = "true", matchIfMissing = false)
public class BackupScheduleConfig {
    
    private final BackupService backupService;
    
    /**
     * 每天凌晨2点执行完整备份
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void dailyFullBackup() {
        log.info("开始执行每日完整备份");
        try {
            OssFileVO backup = backupService.fullBackup();
            if (backup != null) {
                log.info("每日完整备份成功，已上传到OSS: {}", backup.getUrl());
            } else {
                log.error("每日完整备份失败");
            }
        } catch (Exception e) {
            log.error("每日完整备份异常", e);
        }
    }
    
    /**
     * 每6小时执行数据库备份
     */
    @Scheduled(cron = "0 0 */6 * * ?")
    public void databaseBackup() {
        log.info("开始执行数据库备份");
        try {
            OssFileVO backup = backupService.backupDatabase();
            if (backup != null) {
                log.info("数据库备份成功，已上传到OSS: {}", backup.getUrl());
            } else {
                log.error("数据库备份失败");
            }
        } catch (Exception e) {
            log.error("数据库备份异常", e);
        }
    }
    
    /**
     * 每周日凌晨1点清理过期备份（保留30天）
     */
    @Scheduled(cron = "0 0 1 ? * SUN")
    public void cleanupOldBackups() {
        log.info("开始清理过期备份文件");
        try {
            backupService.cleanupOldBackups(30);
            log.info("过期备份文件清理完成");
        } catch (Exception e) {
            log.error("清理过期备份文件异常", e);
        }
    }
}
